// step1 - to create react with vite in offline
npm create vite@latest --offline
// step2 - go to the react file
npm install --offline
// step3 - to run react
npm run dev
const navbar = (
<nav>
<h1>Bob's Bistro</h1>
<ul>
<li>Pricing</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
)
ReactDOM.render(navbar, document.getElementById("root"))
const name = "suji"
const age = 21
function component(){
return(
<p>Greeting {name}!</p>
/* <p>
Age {if(age>20) "Happy"} // this is not allowed
</p>
*/
);
}
<>
// within this we can write multiple html tags
</>
function MyComponent(props){
return(
<p>Hello, {props.name}!
);
}
ReactDOM.createRoot(document.getElementById('root')).render(
<div>
<MyComponent name="Suji" />
</div>
)
function MyComponent({name, job, email, color, fontSize}){
return(
<ul>
<li
style={{
color,
fontSize
}}
>{name}</li>
<li>Job</li>
<li>{job}</li>
<li>Email</li>
<li>{email}</li>
</ul>
);
}
ReactDOM.createRoot(document.getElementById('root')).render(
<>
<MyComponent
name = "Suji"
job = "Software Engineer"
email = "abc@gmail.com"
color = "blue"
fontSize = "20px"
/>
<br/>
<MyComponent
name = "James"
job = "Mech Engineer"
email = "abcdef@gmail.com"
color = "red"
fontSize = "30px"
/>
<br/>
<MyComponent
name = "Jonathan"
job = "Electrical Engineer"
email = "abcdefgh@gmail.com"
color = "green"
fontSize = "40px"
/>
</>
)
// MyComponent.jsx
function MyComponent({name, job, email, color, fontSize}){
return(
<ul>
<li
style={{
color,
fontSize
}}
>{name}</li>
<li>Job</li>
<li>{job}</li>
<li>Email</li>
<li>{email}</li>
<br />
</ul>
);
}
export default MyComponent;
//main.jsx
import MyComponent from './MyComponent.jsx'
const data = [
{
id:"abc123",
name:"suji",
job : "Software Engineer",
email : "abc@gmail.com",
color : "blue",
fontSize : "20px",
},
{
id:"efg456",
name:"James",
job : "Mech Engineer",
email : "abcdef@gmail.com",
color : "red",
fontSize : "30px",
},
{
id:"hij789",
name:"Jonathan",
job : "Electrical Engineer",
email : "abcdefgh@gmail.com",
color : "green",
fontSize : "40px",
},
]
ReactDOM.createRoot(document.getElementById('root')).render(
<>
{data.map((ele) => (
<>
<MyComponent
name = {ele.name}
job = {ele.job}
email = {ele.email}
color = {ele.color}
fontSize = {ele.fontSize}
/>
<br />
</>
))}
</>
)

.map() array method do?Returns a new array. Whatever gets returned from the callback function provided is placed at the same index in the new array. Usually we take the items from the original array and modify them
in some way.
.map() for in React?Convert an array of raw data into an array of JSX elements that can be displayed on the page.
.map() better than just creating the components manually by typing them out?It makes our code more "self-sustaining" - not requiring additional changes whenever the data changes.
// Sidenote.module.css
.title{
color : blue;
}
// App.js
import styles from './sidenote.module.css'
function App(){
return(
<h1 className={style.title}>Heading 1</h1>
)
}
function App(){
function click(){
window.alert('Completion Success');
}
return(
<button onClick={click}> Click me! </button>
// if we don't call them directly it will only call when we click the button
// <button onClick={click()}> Click me! </button>
// if we call function directly then react will call the function even without clicking the button on everytime we open the page
// bcz, react renders them first
)
}
function App(){
function click(type){
if(type === 'success'){
window.alert('Completion Success');
}
else{
window.alert('Completion Dead');
}
}
return(
<button onClick={() => click('success')}> Click me! </button>
// if we don't want to call them directly and also pass values then we use 'another function' within that function we put our 'click func' - like 'callback func'
// This will only call when we click the button
// <button onClick={click('success')}> Click me! </button>
// if we want to pass values throught that func we need to call function directly then react will call the function even without clicking the button on everytime we open the page
// bcz, react renders them first
)
}
setCount(count+1) to update the state.function App() {
const [count, setcount] = useState(0)
function increment(){
setcount(count+1);
alert(count); // here it shows 0, but after clicking 'OK' the 'count' will be incremented in the UI
}
return (
<>
<h1>Count : {count}</h1>
<button onClick={increment}>click me</button>
</>
)
}
function App(){
const [user, setUser] = useState({name:'Suji'});
const [status, setStatus] = useState('ready');
const [msg, setMsg] = useState();
if(!user){
return <p>{msg}</p>;
}
return(
<button
onClick={() => {
setUser(null);
setStatus('initial');
steMsg('You have been logged out.');
}}
> Log out
</button>
);
}
function App() {
const [count, setcount] = useState(0)
function increment(){
const incrementCount = count+1;
setcount(incrementCount);
alert('count :'${incrementCount})
}
return (
<>
<h1>Count : {count}</h1>
<button onClick={increment}>click me</button>
</>
)
}
import React, { useState } from 'react';
function MyComponent() {
const [message, setMessage] = useState('Hello, React!');
return (
<p>{message}</p>;
);
}
import React, { useState } from 'react';
function MyComponent() {
const [inputValue, setInputValue] = useState('');
const handleInputChange = (event) => {
setInputValue(event.target.value);
};
return (
<div>
<input
type="text"
value={inputValue}
// this allows 2-way binding, state to UI
onChange={handleInputChange}
// this allows 2-way binding, UI to state
/>
<p>{inputValue}</p>
// this is 1-way binding, state to UI
</div>
);
}
// data.js
export const countries = {
AF : "Africa",
CH : "China",
IN : "India",
KR : "Korea",
US : "United States - America",
UK : "United Kingdom",
}
//App.js
import { useState } from 'react'
import './App.css'
import { countries } from './data'
function App() {
const [country, setCountry] = useState('IN')
const countryName = Object.entries(countries)
// object.entries(objVar) will return an array of array like this
/* countryName = [
['AF', 'Africa'],
['CH', 'China'],
['IN', 'India'],
['KR', 'Korea']
] */
/* this is destucturing of countryName = [[a1,b1],[a2,b2],[a3,b3]]
countryName.map(([id, label]) => {
['AF', 'Africa']
['CH', 'China']
console.log(label);
}) */
function handleChange(event){
setCountry(event.target.value) // this allows UI to state
}
return (
<>
<form>
<label htmlFor="country">Country :</label>
<br /><br />
<select name="country" id="country"
value={country} // this allows 2-way binding, state to UI
onChange={handleChange} // this allows 2-way binding, UI to state
>
{countryName.map(([id, label]) => {
return (
<option value={id} key={id}>
{label}
</option>
)
})}
</select>
</form>
<p>Selected is : {country}</p>
</>
)
}
export default App
const Correct_code = '12345';
function App(){
const [num, setnum] = useState('0')
function handleChangeNum(event){
setnum(event.target.value)
}
function handleSubmit(event){
event.preventDefault(); // this prevents the form to reload
const isCorrect = num === correct_num;
window.alert(isCorrect ? 'correct!':'error!');
}
return (
<>
<form onSubmit={handleSubmit}>
<input type="text"
value={num}
onChange={handleChangeNum}
/>
<button>Verify</button>
</form>
</>
)
}
export default App
import { useState } from 'react'
function App() {
const [iceCream, seticeCream] = useState("Select")
return (
<>
<form onSubmit={handleSubmit}>
{/* radiobutton */}
<label>Select fav ice-cream: </label>
{/* 'name' used to make the two radio buttons to one group, so we can only select one radio button */}
{/* to select radiobutton by clicking the label, done by 'htmlFor' & 'id' making them to have same name */}
{/* to change the iceCream value in radiobutton, its little diff from others, we need to give accurate value (value='value') rather than seting the useState value */}
<input id='chocolate' type="radio" name='iceCream' value='chocolate'
onChange={(event)=>{seticeCream(event.target.value)}}/>
<label htmlFor="chocolate">Chocolate</label>
<input id='vanilla' type="radio" name='iceCream' value='vanilla' onChange={(event)=>{seticeCream(event.target.value)}}/>
<label htmlFor="vanilla">Vanilla</label>
<p>Your fav IceCream is : {iceCream}</p>
</form>
</>
)
}
// App.jsx
import { useState } from 'react'
import './App.css'
import Promotion from './Promotion'
import Total from './Total'
function App() {
{/* lifting state */}
const [Cnum, setCnum] = useState(0)
const amount = 100 - Cnum
function handleCouponSubmit(couponValue){
setCnum(couponValue)
}
return (
<>
{/* lifting state */}
<h2>This for lifting state example</h2>
<Promotion handleCouponSubmit={handleCouponSubmit}/>
<Total amount={amount}/>
</>
)
}
export default App
// Promotion.jsx
import React, { useState } from 'react'
const Promotion = ({handleCouponSubmit}) => {
const [couponValue, setcouponValue] = useState(0)
return (
<div>
<form onSubmit={(event)=>{
event.preventDefault()
handleCouponSubmit(couponValue)
}}>
<label htmlFor="Cnumber">Enter coupon number :</label>
<input type="text" name='Cnumber' onChange={(event)=>{
setcouponValue(event.target.value)
}}/>
</form>
</div>
)
}
export default Promotion
// Total.jsx
import React, { useState } from 'react'
const Total = ({amount}) => {
return (
<div>
<h3>Total amount is : {amount}</h3>
</div>
)
}
export default Total
const [items,setitems] = useState([])
// derived state
const totalItems = items.length // this gives total no.of items
const totalSelectedItems = items.filter((item) => item.checked).length // this gives total no.of selected items
function App(){
return(
<Button>
This is childre and content of button
</Button>
)
}
function Button(children){
return(
<button style={backgroundColor: "#000", color: "#fff"}>
{children}
</button>
)
}
The useEffect hook in React is used to perform side effects in function components. It allows you to perform tasks that cannot be handled during rendering.
useEffect(() => {
// when component created this 'callback runs'
console.log("component created");
// when a component deleted this 'return callback runs'
return () => {
console.log("component deleted");
};
});
Reduc toolkit is used to implement Redux functionalities for state management
used when we need to change states faster and frequently
used for large applications which provides centralized state management (for small apps we can use ContextAPI)
// /store/store.jsx
import { configureStore } from "@reduxjs/toolkit";
export const store = configureStore({
reducer: {},
});
// main.jsx
import { store } from"./store/store.jsx";
ReactDOM.createRoot(document.getElementById("root")).render(
)
5. ==create new folder "reducer" and "counterSlice.jsx" file== in the "store" folder
6. ==import "creatSlice" from reduxToolkit in "counterSlice.jsx"== as below :
```javascript
// /store/reducer/counterSlice.jsx
import { createSlice } from '@reduxjs/toolkit'; // function or API from redux toolkit
const initialState = {
value: 0,
};
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
// reducer functions or actions
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions; // this generates 'action creators' for each case reducer function
export default counterSlice.reducer; // this generates 'reducers'
// /store/store.jsx
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./reducer/counterSlice.jsx"
export const store = configureStore({
reducer: {
counter : counterReducer, // now counterSlice is imported
},
});
8. ==use Redux State and Action in react component== as below :
1. ==useSelector hook== : to access/read the state from the reducer
2. ==useDispatch== : to access/call the actions from the reducer
```javascript
// App.jsx
import React from 'react';
import { useSelector } from 'react-redux';
import { increment, decrement, incrementByAmount } from './store/reducer/counterSlice'
function App() {
const { value } = useSelector((state) => state.counter); // used to access/read the state from the reducer
const dispatch = useDispatch(); // used to access the actions from the reducer
return (
<div>
<h1>Counter : {value}</h1>
<button
onClick={dipatch(increment())}>
Increment
</button>
<button
onClick={dipatch(decrement())}>
Decrement
</button>
<button
onClick={dipatch(incrementByAmount(5))}>
Increment by 5
</button>
</div>
);
}
export default App;
// asynchronous func
export const incrementAsync = (amount) => (dispatch) => { //higher order function
setTimeout(()=>{
dispatch(incrementByAmount(amount));
}, 2000); //incrementByAmount() will be called using the 'dispatch' which is defaultly gvn by reduxToolkit for using async func
} // we will be calling this 'incrementAsync' in the 'App' component
// /store/reducer/counterSlice.jsx
import { createSlice } from '@reduxjs/toolkit'; // function or API from redux toolkit
const initialState = {
value: 0,
};
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions; // this generates 'action creators' for each case reducer function
// asynchronous func
export const incrementAsync = (amount) => (dispatch) => { //higher order function
setTimeout(()=>{
dispatch(incrementByAmount(amount));
}, 2000); //incrementByAmount() will be called using the 'dispatch' which is defaultly gvn by reduxToolkit for using async func
} // we will be calling this 'incrementAsync' in the 'App' component
export default counterSlice.reducer; // this generates 'reducers'